package com.aplink.generic.util;

import java.util.Locale;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;

public class Language {
    public static final String DEFAULT_LANGUAGE = null;
    public static final String KEY_LANGUAGE = "KEY_LANGUAGE";
    public static final String USER_LANGUAGE = "pick_language";

    public static boolean hasSetLanguage(final Context context) {
        final SharedPreferences pickLanguageSharedPreferences = context
                .getSharedPreferences(Language.USER_LANGUAGE,
                        Context.MODE_PRIVATE);
        final String setLanguage = pickLanguageSharedPreferences.getString(
                Language.KEY_LANGUAGE, null);
        return setLanguage != null;
    }

    public static void saveLanguage(final Context context, final String language) {
        final SharedPreferences pickLanguageSharedPreferences = context
                .getSharedPreferences(Language.USER_LANGUAGE,
                        Context.MODE_PRIVATE);
        final SharedPreferences.Editor myLanguageEditor = pickLanguageSharedPreferences
                .edit();
        myLanguageEditor.putString(Language.KEY_LANGUAGE, language);
        myLanguageEditor.commit();
    }

    private static void setLanguage(final Context context, final String language) {
        if (language != null) {
            final Locale locale = new Locale(language);
            Locale.setDefault(locale);
            final Configuration config = new Configuration();
            config.locale = locale;
            context.getResources().updateConfiguration(config,
                    context.getResources().getDisplayMetrics());
        }
    }

    public static void updateLanguageSystem(final Context context) {
        final SharedPreferences userLanguage = context.getSharedPreferences(
                Language.USER_LANGUAGE, 0);
        final String setLanguage = userLanguage.getString(
                Language.KEY_LANGUAGE, Language.DEFAULT_LANGUAGE);
        if ((setLanguage != null) && !setLanguage.equalsIgnoreCase("default")) {
            Language.setLanguage(context, setLanguage);
        }
    }
}
